<?php

/**
 * 每日次数限制类
 *
 * @author suning <snsnsky@gmail.com>
 *
 * $Id$
 */

namespace Tools;

use \Common\Bridge;

class DateLimit
{
    const REDIS_DB = 4;

    // 参数配置
    public static $coin_conf = [];

    const LIMIT_TIME = 86400;

    /**
     * 检测是否在限制时间内
     *
     * @param int $uid  用户ID
     * @param int $type 类型, 见 center/coin.cfg.php QCOIN_TYPE_*
     * @return bool true:在限制时间内 false:不在限制时间内
     * @throws \Exception
     */
    public static function checkLimit($uid, $type)
    {
        if (!isset(self::$coin_conf[$type])) {
            throw new \Exception('Unsupported Type');
        }

        $count = self::getLimit($uid, $type);

        if ($count >= self::$coin_conf[$type]['limit']) {
            return true;
        }

        return false;
    }

    /**
     * 获得用户当前类型的限制数量
     *
     * @param int $uid  用户ID
     * @param int $type 类型, 见 center/coin.cfg.php QCOIN_TYPE_*
     * @return int 获得计数
     * @throws \Exception
     */
    public static function getLimit($uid, $type)
    {
        if (!isset(self::$coin_conf[$type])) {
            throw new \Exception('Unsupported Type');
        }

        $redis = Bridge::redis(Bridge::REDIS_OTHER_R, self::REDIS_DB);
        $key = self::$coin_conf[$type]['key'] . $uid . ':' . date("Ymd");
        $count = (int)$redis->get($key);

        return $count;
    }

    /**
     * 标记当前类型的限制次数
     *
     * @param int $uid  用户ID
     * @param int $type 类型, 见 center/coin.cfg.php QCOIN_TYPE_*
     * @return int 记录的数量
     * @throws \Exception
     */
    public static function setLimit($uid, $type)
    {
        if (!isset(self::$coin_conf[$type])) {
            throw new \Exception('Unsupported Type');
        }

        $redis = Bridge::redis(Bridge::REDIS_OTHER_W, self::REDIS_DB);
        $key = self::$coin_conf[$type]['key'] . $uid . ':' . date("Ymd");
        $ret = $redis->incr($key);
        if ($ret == 1) {
            $redis->expire($key, self::LIMIT_TIME);
        }

        return $ret;
    }
}

DateLimit::$coin_conf = loadconf('center/coin');